<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>getHorizontalOffset</title>
    <style>
        .test {
            position: absolute;
            top: 150px;
            left: 100px;
            width: 100px;
            height: 100px;
            border: 1px solid #2396ef;
        }
    </style>
</head>

<body>
    <div id="test" class="test"></div>
    <script>
        const getHorizontalOffset = el => {
            let offsetLeft = el.offsetLeft,
                _el = el;
            while (_el.offsetParent) {
                _el = _el.offsetParent;
                offsetLeft += _el.offsetLeft;
            }
            return offsetLeft;
        };
        const test = document.querySelector('#test');
        test.textContent = '元素距离最左边的距离为:' + getHorizontalOffset(test);
    </script>
</body>

</html>